#!/bin/bash

let "args=$2+2"
if [ $# -ne $args ]
then
    echo "Usage:: ./predict /path/data.csv NO_of_Attributes(n) Attr1 Attr2 .... Attrn"
    exit 1
fi

echo "">1.txt

for index in $(seq 3 $#)
do
    #echo ${!index}
    export attr=${!index}
    awk -F',' '{ print $ENVIRON["attr"] }' $1 >2.txt
    paste 1.txt 2.txt >3.txt
    mv 3.txt 1.txt
    rm 2.txt    
done

#denoising the file
awk  '{gsub("\t"," ",$0); print;}' 1.txt > 3.txt #replace <space TAB> with <space>
cat 3.txt |sed 's/^ //g' >1.txt
rm 3.txt


 awk '{s=0;for (i=1; i<=NF; i++){ s=s+1; print (s-1)":"$s;} print "@"}' 1.txt >2.txt

cat 2.txt |sed ':a;N;$!ba;s/\n/ /g' >1.txt
#cat 1.txt |sed ':a;N;$!ba;s/@/\n /g' >2.txt
tr '@' '\n' < 1.txt >2.txt
cat 2.txt | sed 's/ 0://g'|sed '/^$/d'>1.txt

#xtracting last day data for prediction
cat 1.txt | sed -e :a -e '$q;N;97,$D;ba' >test.txt
#extracting data for training
cat 1.txt | sed '1d' | sed -n -e :a -e '1,96!{P;N;D;};N;ba' >train.txt

./svm/svm-train -s 3 -t 2 -b 0 -q train.txt model.text
./svm/svm-predict test.txt model.text output.txt

cat test.txt | awk '{print $1}' >1.txt
paste 1.txt output.txt >predictedValues.txt

# awk '{s+=$1}END {printf("sum=%f Average=%f\n",s,s/NR)}' predictedValues.txt 

MAPE=`awk 'BEGIN {sum=0;MAPE=0;}{val=(($1-$2)/$1); if(val<0){val=val*-1;}else{val=val} sum+=val; } END {MAPE=(sum/NR)*100; print MAPE}' <predictedValues.txt`
echo $MAPE"*" >>CombinationResult.txt
echo $MAPE
rm 1.txt 2.txt 
